#!/usr/bin/env python3

# Copyright (c) 2020-2021 Fpemud <fpemud@sina.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.


from .._util import WinFile
from .._const import Lang
from ._spec import Spec


class AnswerFile(WinFile):

    def __init__(self, ts):
        self._ts = ts

        self.installOptions = None

        self.computerName = None

        self.joinDomain = None

        self.enableDefender = True          # Windows Defender enabled/disabled
        self.enableCloud = True             # Cloud consumer features enabled/disabled
        self.enableRemoteDesktop = False    # Remote desktop enabled/disabled
        self.enableServerManager = True     # Server Manager enabled/disabled

    def get_filename(self):
        # unattend.xml can not be used in <windowsPE> stage and <offlineServicing> stage
        # autounattend.xml is to be used in all stages
        return "autounattend.xml"

    def get_content(self):
        spec = Spec(self._ts.arch)

        # assign values
        self.productId = self._ts.product_key

        buf = self._template
        buf = buf.replace("@@component_tag_postfix@@", " ".join([
                'processorArchitecture="%s"' % (spec.archDict[self._ts.arch]),
                'publicKeyToken="31bf3856ad364e35"',
                'language="neutral"',
                'versionScope="nonSxS"',
                'xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"',
            ])
        )
        buf = buf.replace("@@arch@@", spec.archDict[self._ts.arch])
        buf = buf.replace("@@pe_lang@@", spec.langDict[Lang.en_US])                  # use fixed PE language, no one reads it ;)
        buf = buf.replace("@@pe_input_lang@@", spec.localeCodeDict[Lang.en_US])      # same above
        buf = buf.replace("@@lang@@", spec.langDict[self._ts.lang])
        buf = buf.replace("@@username@@", "A")
        buf = buf.replace("@@password@@", "")
        buf = buf.replace("@@product_key@@", self.productId)
        buf = buf.replace("@@timezone@@", spec.timezoneDict[self._ts.lang])

        return buf

    _template = """
<?xml version="1.0" encoding="utf-8"?>
<unattend xmlns="urn:schemas-microsoft-com:unattend" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State">
    <settings pass="windowsPE">
        <component name="Microsoft-Windows-International-Core-WinPE" @@component_tag_postfix@@>
            <SetupUILanguage>
                <UILanguage>@@pe_lang@@</UILanguage>
            </SetupUILanguage>
            <InputLocale>@@pe_input_lang@@</InputLocale>
            <SystemLocale>@@pe_lang@@</SystemLocale>
            <UILanguage>@@pe_lang@@</UILanguage>
            <UILanguageFallback>@@pe_lang@@</UILanguageFallback>
            <UserLocale>@@pe_lang@@</UserLocale>
        </component>
        <component name="Microsoft-Windows-Setup" @@component_tag_postfix@@>
            <DiskConfiguration>
                <Disk>
                    <DiskID>0</DiskID>
                </Disk>
                <WillShowUI>OnError</WillShowUI>
            </DiskConfiguration>
            <ImageInstall>
                <OSImage>
                    <InstallTo>
                        <DiskID>0</DiskID>
                        <PartitionID>1</PartitionID>                                            <!-- the first partition -->
                    </InstallTo>
                    <WillShowUI>OnError</WillShowUI>
                </OSImage>
            </ImageInstall>
            <UserData>
                <ProductKey>
                    <Key>@@product_key@@</Key>
                    <WillShowUI>OnError</WillShowUI>
                </ProductKey>
                <AcceptEula>true</AcceptEula>
                <FullName>@@username@@</FullName>
            </UserData>
        </component>
    </settings>
    <settings pass="oobeSystem">                                                                <!-- system Out-Of-Box-Experience -->
        <component name="Microsoft-Windows-International-Core" @@component_tag_postfix@@>
            <InputLocale>@@pe_input_lang@@</InputLocale>
            <SystemLocale>@@pe_lang@@</SystemLocale>
            <UILanguage>@@pe_lang@@</UILanguage>
            <UILanguageFallback>@@pe_lang@@</UILanguageFallback>			<!-- fixme, really needed? -->
            <UserLocale>@@pe_lang@@</UserLocale>
        </component>
        <component name="Microsoft-Windows-Shell-Setup" @@component_tag_postfix@@>
            <OOBE>
                <HideEULAPage>true</HideEULAPage>
                <HideWirelessSetupInOOBE>true</HideWirelessSetupInOOBE>
                <NetworkLocation>Other</NetworkLocation>
                <ProtectYourPC>1</ProtectYourPC>
                <SkipUserOOBE>true</SkipUserOOBE>
                <SkipMachineOOBE>true</SkipMachineOOBE>
            </OOBE>
            <TimeZone>@@timezone@@</TimeZone>
            <UserAccounts>
                <LocalAccounts>
                    <LocalAccount wcm:action="add">
                        <Group>Administrators</Group>
                        <Name>@@username@@</Name>
                        <Password>
                            <Value>@@password@@</Value>
                            <PlainText>true</PlainText>
                        </Password>
                    </LocalAccount>
                </LocalAccounts>
            </UserAccounts>
        </component>
    </settings>
    <settings pass="specialize">
        <component name="Microsoft-Windows-Shell-Setup" @@component_tag_postfix@@>
            <ComputerName>@@username@@-PC</ComputerName>
        </component>
        <component name="Microsoft-Windows-IE-InternetExplorer" @@component_tag_postfix@@>      <!-- disable the welcome window of IE -->
            <DisableAccelerators>true</DisableAccelerators>
            <DisableOOBAccelerators>true</DisableOOBAccelerators>
            <SuggestedSitesEnabled>false</SuggestedSitesEnabled>
            <Home_Page>about:blank</Home_Page>
        </component>
    </settings>
</unattend>
        """


class GuiRunOnceBatchFile(WinFile):

    def __init__(self):
        self._cmdList = []

    def get_filename(self):
        return "RUNONCE.BAT"

    def add_command(self, command):
        self._cmdList.append(command)

    def get_content(self):
        buf = ""
        for cmd in self._cmdList:
            buf += "%s\n" % (cmd)
        return buf
